package cn.bonoon.kernel.expression.resolver;

import cn.bonoon.kernel.IdGenerator;
import cn.bonoon.kernel.expression.ExpressionParseContext;
import cn.bonoon.kernel.expression.QueryExpressionParameter;
import cn.bonoon.kernel.expression.QueryExpressionParameterMode;
import cn.bonoon.kernel.expression.results.ObjectExpressionValue;
import cn.bonoon.kernel.expression.results.RequestExpressionValue;

public class ModelExpressionResolver extends AbstractExpressionPropertyResolver{

	ModelExpressionResolver(){
		super("MODEL");
	}

	@Override
	protected boolean internalResolver(ExpressionParseContext context, String[] commands) throws Exception {
		String velocityExpression = null, 
				//用于传值的参数名
				fieldName = null, 
				type = null, 
				mode = null;
		
		for(int i = 1; i < commands.length; i++){
			String tmp = commands[i];
			
			if(tmp.startsWith("-")){
				type = tmp.substring(1).toUpperCase();
				continue;
			}

			if(tmp.startsWith("#")){
				mode = tmp.substring(1).toUpperCase();
				continue;
			}

			if(null == velocityExpression){
				velocityExpression = tmp;
				continue;
			}

			if(null == fieldName){
				fieldName = tmp;
				continue;
			}
		}
		
		if(null != mode){
			if(null == fieldName){
				fieldName = IdGenerator.fixed();//生成一个id
			}
			
			context.parameter(new QueryExpressionParameter(fieldName, velocityExpression, QueryExpressionParameterMode.valueOf(mode)));
		}else{
			//如果只有一个值的话，一定是"velocityExpression"有值，所以直接判断"fieldName"是否为空即可
			if(null != fieldName){
				context.parameter(new QueryExpressionParameter(fieldName, velocityExpression, QueryExpressionParameterMode.PROPERTY));
			}else{
				fieldName = velocityExpression;
			}
		}
		
		if("O".equals(type)){
			context.value(new ObjectExpressionValue(context, fieldName));
		}else{
			context.value(new RequestExpressionValue(context, fieldName, type));
		}
		
		return super.internalResolver(context, commands);
	}
}
